#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

char buf[1024] = {0};
pthread_rwlock_t rwlock;

void *write0(void *arg)
{
    while(1)
    {
        pthread_rwlock_wrlock(&rwlock); //写锁
        strcpy(buf, "你好啊！");
        pthread_rwlock_unlock(&rwlock); //解锁
    }
}

void *write1(void *arg)
{
    while(1)
    {
        pthread_rwlock_wrlock(&rwlock); //写锁
        strcpy(buf, "hello world!");
        pthread_rwlock_unlock(&rwlock); //解锁
    }
}

void *write2(void *arg)
{
    while(1)
    {
        pthread_rwlock_wrlock(&rwlock); //写锁
        strcpy(buf, "今天天气真好！");
        pthread_rwlock_unlock(&rwlock); //解锁
    }
}
int main(int argc, char const *argv[])
{
    pthread_t tid1, tid2, tid3;
    pthread_create(&tid1, NULL, write0, NULL);
    pthread_create(&tid2, NULL, write1, NULL);
    pthread_create(&tid3, NULL, write2, NULL);

    sleep(1);

    while(1)
    {
        pthread_rwlock_rdlock(&rwlock);
        printf("buf = %s\n", buf);
        pthread_rwlock_unlock(&rwlock);
    }
    
    return 0;
}
